package com.example.consumer.config;

import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.Exchange;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.core.TopicExchange;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.lang.Nullable;

import java.util.HashMap;
import java.util.Map;

/**
 * @description:
 * @program: demos
 * @author: dove
 * @date: 2020-12-09 00:35
 * 采用json格式的序列化器，mq中的消息存放的是json格式的数据，而不是二进制数据
 **/

@Configuration
public class MyRabbitMQConfig {

    @Bean
    public MessageConverter getMessageConverter(){
        return new Jackson2JsonMessageConverter();
    }

    /**
     * 死信路由
     * @return
     */
    @Bean
    public Exchange exchange(){
//        TopicExchange(String name, boolean durable, boolean autoDelete)
        return new TopicExchange("common.exchange",true,false);
    }

    @Bean
    public Queue dealQueue(){
//        Queue(String name, boolean durable, boolean exclusive, boolean autoDelete, @Nullable Map<String, Object> arguments)
        return new Queue("deal.queue",true,false,false);
    }

    @Bean
    public Queue deadQueue(){
        Map<String,Object> arguments = new HashMap<>();
        arguments.put("x-dead-letter-exchange","common.exchange");
        // 死信到期，路由到exchange，指定路由键为dealQueue的路由键
        arguments.put("x-dead-letter-routing-key","deal.routingKey");
        arguments.put("x-message-ttl",120000); // 2分钟
        return new Queue("dead.letter.queue", true, false,false, arguments);
    }

    /**
     * *:只能匹配一个单词
     * #：匹配0个或多个单词
     * @return
     */
    @Bean
    public Binding dealQueueBindExchang(){
//        Binding(String destination, Binding.DestinationType destinationType, String exchange, String routingKey, @Nullable Map<String, Object> arguments)
        return new Binding("deal.queue",Binding.DestinationType.QUEUE,"common.exchange","deal.routingKey.#",null);
    }

    @Bean
    public Binding deadQueueBindExchange(){
        return new Binding("dead.queue",Binding.DestinationType.QUEUE,"common.exchange","dead.routingKey",null);
    }
}
